package com.c2b.algorithm.leetcode.base;

import java.util.LinkedList;
import java.util.Queue;

/**
 * <a href="https://leetcode.cn/problems/same-tree/">相同的树(Same Tree)</a>
 * <p>给你两棵二叉树的根节点 p 和 q ，编写一个函数来检验这两棵树是否相同。</p>
 * <p>如果两个树在结构上相同，并且节点具有相同的值，则认为它们是相同的。</p>
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：p = [1,2,3], q = [1,2,3]
 *      输出：true
 *
 * 示例 2：
 *      输入：p = [1,2], q = [1,null,2]
 *      输出：false
 *
 * 示例 3：
 *      输入：p = [1,2,1], q = [1,1,2]
 *      输出：false
 * </pre>
 * </p>
 * <p>
 * <b>提示：</b>
 *     <ul><li>两棵树上的节点数目都在范围 [0, 100] 内</li><li>-10^4 <= Node.val <= 10^4</li></ul>
 * </p>
 *
 * @author c2b
 * @since 2023/5/11 9:40
 */
public class LC0100SameTree_S {

    static class Solution {
        public boolean isSameTree(TreeNode p, TreeNode q) {
            return isSameTreeByIteration(p, q);
            //return isSameTreeByRecursion(p, q);
        }

        private boolean isSameTreeByRecursion(TreeNode p, TreeNode q) {
            if (p == null && q == null) {
                return true;
            }
            if (p == null || q == null || p.val != q.val) {
                return false;
            }
            return isSameTreeByRecursion(p.left, q.left) && isSameTreeByRecursion(p.right, q.right);
        }

        private boolean isSameTreeByIteration(TreeNode p, TreeNode q) {
            if (p == null && q == null) {
                return true;
            }
            if (p == null || q == null) {
                return false;
            }
            Queue<TreeNode> pQueue = new LinkedList<>();
            pQueue.offer(p);
            Queue<TreeNode> qQueue = new LinkedList<>();
            qQueue.offer(q);
            while (!pQueue.isEmpty() && !qQueue.isEmpty()) {
                TreeNode pTemp = pQueue.poll();
                TreeNode qTemp = qQueue.poll();
                if (pTemp == null && qTemp == null) {
                    continue;
                }
                if (pTemp == null || qTemp == null || pTemp.val != qTemp.val) {
                    return false;
                }
                pQueue.offer(pTemp.left);
                pQueue.offer(pTemp.right);
                qQueue.offer(qTemp.left);
                qQueue.offer(qTemp.right);
            }
            return pQueue.isEmpty() && qQueue.isEmpty();
        }
    }

    public static void main(String[] args) {
        TreeNode p = new TreeNode(1);
        p.left = new TreeNode(2);
        p.right = new TreeNode(3);
        p.left.left = new TreeNode(4);
        TreeNode q = new TreeNode(1);
        q.left = new TreeNode(2);
        q.right = new TreeNode(3);
        Solution solution = new Solution();
        System.out.println(solution.isSameTree(p, q));
    }

}
